﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace DownLoadHttp
{
    public partial class MainForm : Form
    {
        string url = ""; string filepath = "";
        HttpDownLoad httpdown = new HttpDownLoad();

        public MainForm()
        {
            Control.CheckForIllegalCrossThreadCalls = false;

            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            //this.txtSrcAddress.Text = @"";// 路径自己填
            this.txtTarAddress.Text = @"D:";
            httpdown.onpr = onProcess;
            btnDown_Click(null, null);// 自动下载
        }
        

        private void btnDown_Click(object sender, EventArgs e)
        {           
            Thread th = new Thread(new ThreadStart(this.StartDownLoad));
            th.Start();

            //ThreadPool.QueueUserWorkItem(new WaitCallback(Thread_CheckNet));
        }

        private void StartDownLoad()
        {           
            this.btnDown.Text = "下载";

            url = this.txtSrcAddress.Text;
            //textBox1.Text = httpdown.getFileName(url);
            //截取文件名称
            string fileName = httpdown.getFileName(url);

            //保存的路径+\文件名
            string dir = this.txtTarAddress.Text;
            filepath = dir + "\\tmp\\ttt\\aaaa\\" + fileName;

            httpdown.httpDownFile(url, filepath);   
            if(httpdown.downOK)
            {
                toolStripStatusLabel.Text = "下载完成";
            }
        }

        private void onProcess(int val,string msg)
        {
            toolStripStatusLabel.Text = msg;
            toolStripProgressBar.Value = val;
        }

        void Thread_CheckNet(object obj)
        {
            HttpDownLoad httpdown = new HttpDownLoad();
            while (true)
            {
                Thread.Sleep(50);

                if (HttpDownLoad.stopDown)
                {
                    if (0 != httpdown.getDownLength(url))
                    {
                        lblMsg.Text = "网络恢复,继续下载!";
                        httpdown.httpDownFile(url, filepath);
                    }
                    else
                    {
                        lblMsg.Text = "网络异常,停止下载!";
                    }
                }
            }
        }

        private void btnPause_Click(object sender, EventArgs e)
        {            
            HttpDownLoad.stopDown = true;
            this.btnDown.Text = "继续下载";
        }
    }
}
